<?php
// +----------------------------------------------------------------------
// |  [ MAKE YOUR WORK EASIER]
// +----------------------------------------------------------------------
// | Copyright (c) 2003-2016 http://www.nbcc.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: fangrenfu <fangrenfu@126.com>
// +----------------------------------------------------------------------

namespace app\common\access;

use think\Collection;
use think\db\Query;
use think\Exception;
use think\exception\DbException;
use think\exception\PDOException;
use think\Log;
use think\Model;

class MyQuery extends  Query
{
    /**
     * 批处理执行SQL语句
     * 批处理的指令都认为是execute操作
     * @access public
     * @param array $sql SQL批处理指令
     * @return boolean
     */
    public function batchQuery($sql = [], $bind = [])
    {
        config('auth')&&MyAccess::checkAccess('E');
        return parent::batchQuery($sql,$bind);
    }

    /**
     * 插入记录
     * @access public
     * @param mixed $data 数据
     * @param boolean $replace 是否replace
     * @param boolean $getLastInsID 是否获取自增ID
     * @param string $sequence 自增序列名
     * @return integer
     */
    public function insert(array $data=[], $replace = false, $getLastInsID = false, $sequence = null)
    {
        config('auth')&&MyAccess::checkAccess('A');
        return parent::insert($data,$replace,$getLastInsID,$sequence);
    }

    /**
     * 批量插入记录
     * @access public
     * @param mixed $dataSet 数据集
     * @return integer
     */
    public function insertAll(array $dataSet,$replace=false,$limit = null)
    {
        config('auth')&&MyAccess::checkAccess('A');
        return parent::insertAll($dataSet,$replace,$limit);
    }

    /**
     * 通过Select方式插入记录
     * @access public
     * @param string $fields 要插入的数据表字段名
     * @param string $table 要插入的数据表名
     * @return int
     * @throws PDOException
     */
    public function selectInsert($fields, $table)
    {
        config('auth')&&MyAccess::checkAccess('A');
        return parent::selectInsert($fields,$table);
    }

    /**
     * 更新记录
     * @access public
     * @param mixed $data 数据
     * @return int
     * @throws Exception
     * @throws PDOException
     */
    public function update(array $data=[])
    {
        config('auth')&&MyAccess::checkAccess('M');
        return parent::update($data);
    }

    /**
     * 查找记录
     * @access public
     * @param array|string|Query|\Closure $data
     * @return Collection|false|\PDOStatement|string
     * @throws DbException
     * @throws Exception
     * @throws PDOException
     */
    public function select($data= null)
    {
        config('auth')&&MyAccess::checkAccess('R');
        return parent::select($data);
    }
    /**
     * 查找单条记录
     * @access public
     * @param array|string|Query|\Closure $data
     * @return array|false|\PDOStatement|string|Model
     * @throws DbException
     * @throws Exception
     * @throws PDOException
     */
    public function find($data= null)
    {
        config('auth')&&MyAccess::checkAccess('R');
        return parent::find($data);
    }

    /**
     * 删除记录
     * @access public
     * @param array $data 表达式
     * @return int
     * @throws Exception
     * @throws PDOException
     */
    public function delete($data =null)
    {

        config('auth')&&MyAccess::checkAccess('D');
        return parent::delete($data);
    }
    //重写field方法，以支持sql语句两个以上参数的函数使用，如 isnull(mon,0)，官方仅支持数组方式。
    public function field($field, $except = false, $tableName = '', $prefix = '', $alias = '')
    {
        if (empty($field)) {
            return $this;
        }
        if (is_string($field)) {
            //正则表达式临时替换函数内的逗号
            for($i=0;$i<3;$i++)
                $field=preg_replace("/(\()([^\(]*?)(,)([^\),\(]*?)([\),])/",'$1$2##$4$5',$field);

            $field = array_map('trim', explode(',', $field));
            //将临时替换的逗号转换回来
            $field=preg_replace("/##/",',',$field);
        }
        if (true === $field) {
            // 获取全部字段
            $fields = $this->getTableInfo($tableName ?: (isset($this->options['table']) ? $this->options['table'] : ''), 'fields');
            $field  = $fields ?: ['*'];
        } elseif ($except) {
            // 字段排除
            $fields = $this->getTableInfo($tableName ?: (isset($this->options['table']) ? $this->options['table'] : ''), 'fields');
            $field  = $fields ? array_diff($fields, $field) : $field;
        }
        if ($tableName) {
            // 添加统一的前缀
            $prefix = $prefix ?: $tableName;
            foreach ($field as $key => $val) {
                if (is_numeric($key)) {
                    $val = $prefix . '.' . $val . ($alias ? ' AS ' . $alias . $val : '');
                }
                $field[$key] = $val;
            }
        }

        if (isset($this->options['field'])) {
            $field = array_merge($this->options['field'], $field);
        }
        Log::write($field);
        $this->options['field'] = array_unique($field);
        return $this;
    }
}
